<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8" %>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<c:set var="ctxPath" value="${pageContext.request.contextPath}"/>

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <title>部门列表</title>
    <link rel="stylesheet" href="${ctxPath}/static/layui/css/layui.css?t=1554901098009" media="all">
    <link rel="stylesheet" href="${ctxPath}/static/css/dept.css"/>
    <script src="${ctxPath}/static/js/form.js"></script>

    <style>
        body {
            margin: 10px;
        }

        .demo-carousel {
            height: 200px;
            line-height: 200px;
            text-align: center;
        }

        .layui-input-inline input {
            border: 1px solid #666;
        }
    </style>

</head>
<body>

<script>
    function createUser() {
        window.location = "${ctxPath}/User/viewAddUser";
    }
</script>
<style>
    #tbl {
        margin-left: 25px;
    }

    body {
        background: #F2F2F2;
    }
</style>

<table class="layui-hide" id="demo" lay-filter="test">
</table>

<script type="text/html" id="barDemo">
    <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>

<script src="${ctxPath}/static/layui/layui.js?t=1554901098009" charset="utf-8">
</script>
<script src="${ctxPath}/static/js/jquery-3.6.1.min.js"></script>
<script src="${ctxPath}/static/js/form.js"></script>
<link rel="stylesheet" href="${ctxPath}/static/layui/css/layui.css"/>
<link rel="stylesheet" href="${ctxPath}/static/css/table.css"/>
<script>
    layui.config({
        version: '1554901098009' //为了更新 js 缓存，可忽略
    });

    layui.use(
        ['layer'],
        function () {
            var layer = layui.layer;
        }
    );
</script>

<!-- {ps} 编写我们的 js 代码! -->
<script>


    function reloadPage(op) {
        window.location = '${ctxPath}/Dept/viewList?op=' + op;
    }
</script>

<script>
    function makeRow(_dept) {
        var $UL = $("<ul></ul>");
        $UL.attr("id", "ul_" + _dept.id);
        $UL.attr("class", "item " + "lv" + _dept.level);
        var $dId = $("<li>" + _dept.id + "</li>");
        var $title = makeTitle(_dept);
        var $deptDesc = $("<li>" + _dept.deptDesc + "</li>");
        var $ops = makeOpLI(_dept.id, _dept.isLeap);
        $UL.append($dId);
        $UL.append($title);
        $UL.append($deptDesc);
        $UL.append($ops);
        return $UL;
    }

    function makeTitle(_dept) {
        var $LI = $("<li></li>");
        var $div = $("<div></div>");
        var $sp = $("<span>" + _dept.deptName + "</span>");
        var btn = (_dept.isLeap == true) ? 'btnOpen' : 'btnClose ';
        $div.attr("class", "mi_btn " + btn);
        $div.attr("onclick", "getSub('" + _dept.id + "','" +
            _dept.level + "');");
        $LI.append($div);
        $LI.append($sp);
        return $LI;
    }

    function makeOpLI(deptId, isLeap) {
        var dom = document.createElement("li");
        var $LI = $(dom);
        $LI.append(makeButton('btnEdit', 'doEdit', deptId));
        $LI.append(makeButton('btnDel', 'doDel', deptId));
        $LI.append(makeButton('btnAdd', 'addSub', deptId));
        $LI.append(makeHidden(deptId, deptId));
        //lid:  hd d05_isLeap: true/false
        $LI.append(makeHidden(deptId + '_isLeap', isLeap));
        return $LI;
    }

    function makeHidden(_id, _value) {
        var dom = document.createElement("input");
        var $hdn = $(dom);
        $hdn.attr("id", "hd_" + _id);
        $hdn.attr("type", "hidden");
        $hdn.attr("value", _value);
        return $hdn;
    }

    function makeButton(_class, _method, _deptId) {
        var dom = document.createElement("div");
        var $btn = $(dom);
        $btn.attr("class", "btn " + _class);
        $btn.attr("onclick", _method + "('" + _deptId + "');");
        return $btn;
    }

    function initTree(_cur, _list, _level, _$div) {
        _cur.level = _level;
        for (var i = 0; i < _list.length; i++) {
            var n = _list[i];
            if (n.parentId == _cur.id) {
                _cur.child.push(n);
                console.log("{DATA} push:%s = %s",
                    n.id, n.deptName);
                gridData[n.id] = n;
            }
        }
        if (_cur.child.length == 0) {
            _cur.isLeap = true;
            var $cldUL = makeRow(_cur);
            _$div.append($cldUL);
            return;
        }
        var dBox = document.createElement("div");
        var $dBox = $(dBox);
        var $UL = makeRow(_cur);
        var clds = _cur.child;
        var div = document.createElement("div");
        var $div = $(div);
        $div.attr("id", "dv_" + _cur.id);
        $dBox.append($UL);
        $dBox.append($div);
        for (var j = 0; j < clds.length; j++) {
            var ch = clds[j];
            var d = initTree(ch, _list, _level + 1, $div);
            if (d) {
                $div.append(d);
            }
        }
        return $dBox;
    }

    var gRoot = null;        //根节点..
    function getSub(_deptId, _lv) {
        let child = $("#dv_" + _deptId)
        let root = $("#ul_" + _deptId).children(1)
        let t = root.children(1);
        if (child.children().length !== 0) {
            if (child.css("display") === 'block') {
                t.addClass('btnOpenn')
                t.removeClass('btnClose')
                child.hide()
            } else {
                t.addClass('btnClose')
                t.removeClass('btnOpenn')
                child.show()
            }
        }

    }

    var gridData = {};

    function loadData() {
        $.ajax(
            {
                url: '${ctxPath}/Dept/jsonList',
                type: 'get',
                dataType: 'json',
                success: function (resp) {
                    layer.msg("加载数据成功..");
                    var _list = resp['data'];
                    onReceived(_list);
                }
            }
        );
    }

    function onReceived(_list) {
        for (var i = 0; i < _list.length; i++) {
            var n = _list[i];
            if (n.id === 'sys') {
                continue;
            }
            if (n.parentId === 'top') {
                gRoot = n;
            }
            n.child = [];
            n.isLeap = false;
            gridData[n.id] = n;
        }
        var $div = initTree(gRoot, _list, 1);
        $('#tbl').append($div);
        console.log(gridData);
    }

    $(loadData);


    var gRoot = null;        //根节点..
    var depts = [];

    function addSub(deptId) {
        console.log(deptId)
        window.location = "${ctxPath}/Dept/viewAdd?id=" + deptId;
    }

    function doDel(deptId) {
        if (confirm("您确定要删除吗？")) {
            $.ajax({
                url: '${ctxPath}/Dept/delete?id=' + deptId,
                type: 'get',
                dataType: 'json',
                success: function (resp) {
                    console.log(resp['data']);
                    var ret = resp['result'];
                    if (ret === 'success') {
                        alert('删除部门成功。');
                        //{ps}查看我发起的任务。
                        setTimeout(reloadPage, 1000);
                    } else {
                        layer.msg("删除部门失败:" + resp['cause']);
                    }
                }
            });
        }
    }

    function doEdit(deptId) {
        $.ajax({
            url: '${ctxPath}/Dept/getDeptById?id=' + deptId,
            type: 'post',
            dataType: 'json',
            success: function (resp) {
                var ret = resp['result'];
                if (ret === 'success') {
                    console.log(resp['data'])
                    showPopBox(resp['data']);
                } else {
                    layer.msg("获取房间失败:" + resp.cause);
                }
            }
        });
    }

    var gInputs = [
        {title: '部门Id', name: 'id', type: 'text', readonly: 'readonly'},
        {title: '部门名称', name: 'deptName', type: 'text'},
        {title: '部门备注', name: 'deptDesc', type: 'text'},
        {name: 'parentId', type: 'hide'},
        {name: 'pids', type: 'hide'},
        {name: 'id', type: 'hide'}
    ];

    function showPopBox(dept) {
        var HTML = makeTable(gInputs, dept);
        layer.open({
            type: 1
            , title: '编辑部门'      //显示标题栏
            , closeBtn: false
            , area: ['450px', '380px']
            , shade: 0
            , id: 'LAY_layuipro'   //设定一个 id, 防止重复弹出
            , btn: ['保存数据', '关闭对话框']  //{ps} 两个按钮
            , btnAlign: 'c'        //居中对齐
            , moveType: 1        //拖拽模式, 0 或者 1
            , content: HTML        //这是上面生成的表格 html 代码
            , yes: function () {
                saveDept();
            }
            , success: function (layero) {
                //--暂时不写代码--
            }
        });
    }

    var items = ['id', 'deptName', 'deptDesc', 'parentId', 'pids'];

    function saveDept() {
        let dept = pickData(items);
        console.log(dept);
        $.ajax({
            url: '${ctxPath}/Dept/saveDept',
            type: 'post',
            data: dept,
            dataType: 'json',
            success: function (resp) {
                var ret = resp['result'];
                if (ret === 'success') {
                    layer.msg('保存数据成功。');
                    setTimeout(reloadPage, 2000);
                } else {
                    layer.msg('保存数据失败, 原因:' + resp.cause);
                }
            }
        });
    }
</script>



<div id="tbl">
    <ul id="title" class="item">
        <li>部门ID</li>
        <li>部门名称</li>
        <li>备注</li>
        <li>操作</li>
    </ul>
</div>

</body>
</html>        
